#include <stdio.h>
#include <stdlib.h>
#include "slist.h"


// frist static function to create a new node
// only use in this file
static sNode_t *newNode(int x) {
    sNode_t *node = (sNode_t *)malloc(sizeof(sNode_t));
    if (node != NULL) {
        node->data = x;
        node->next = NULL;
    }
    return node;
}


//insert x after prevNode
void insertAfter(sNode_t *prevNode, int x) {
    sNode_t *node = newNode(x);
    if (!node) return;
    if (prevNode == NULL) {
        prevNode = node;
        node->next = prevNode;
    } else {
        node->next = prevNode->next;
        prevNode->next = node;
    }
}

//insert x at front
void insertAtFront(slist_t *list, int x) {
    sNode_t *node = newNode(x);
    if (!node) return;

    if ( !list->head ) { //head==NULL
        list->head = node;
        list->tail = node;
        node->next = node;
    } else {
        node->next = list->head;
        list->tail->next = node; 
        list->head = node;
    }
} 


//insert node at tail
void insertAtTail(slist_t *list, int x) {
    sNode_t *node = newNode(x);
    if (!node) return;

    if (!list->head) {//head == NULL
        list->head = node;
        list->tail = node;
        node->next = node;
    } else {
        node->next = list->head;
        list->tail->next = node;
        list->tail = node; 
    }
}

//delete a node from front
sNode_t * deleteFromFront(slist_t *list){
    if (!list->head) return 0;

    sNode_t *frontNode = list->head;
    if (list->head == list->tail) { //only one node in list
        list->head = NULL;
        list->tail = NULL;
    } else { 
        list->head = list->head->next;
    }
    return frontNode;
}

void printList(slist_t *list) {
    sNode_t *ptrNode = list->head;

    if (!ptrNode) {
        printf("list is empty\n");
        return;
    }
    while(ptrNode != list->tail) {
        printf("%d ", ptrNode->data);
        ptrNode = ptrNode->next;
    }
    printf("%d\n", ptrNode->data);
}
